#include "xvideo_view.h"
#include "xsdl.h"
#include <chrono>
#include <stdint.h>
#include <thread>
extern "C"
{
#include "libavutil/frame.h"
}
#pragma comment(lib, "avutil.lib")
using namespace std;

///////////////////////////////////////////
///// 视屏渲染接口类
///// 1.隐藏SDL实现
///// 2.渲染方案可替代
///// 3.线程安全
void MSleep(uint64_t ms)
{
  // std::this_thread::sleep_for(std::chrono::milliseconds(ms));
  auto beg = clock();
  for (int i = 0; i < ms; ++i)
  {
    std::this_thread::sleep_for(1ms);
    if ((clock() - beg) / (CLOCKS_PER_SEC / 1000) > ms)
    {
      break;
    }
  }
}
XVideoView *XVideoView::Create(RenderType type)
{
  switch (type)
  {
  case RenderType::SDL:
    return new XSDL();
    break;
    // case RenderType::XV: return new XVideoView();break;
    // case RenderType::QT: return new SdlQtRGB();break;
  }
  return nullptr;
}

bool XVideoView::DrawFrame(AVFrame *frame)
{
  if (!frame || !frame->data[0])
    return false;
  count_++;
  if (beg_ms_ <= 0)
  {
    beg_ms_ = clock();
  }
  // 计算帧率
  else if ((clock() - beg_ms_) / (CLOCKS_PER_SEC / 1000) >= 1000)
  {
    render_fps_ = count_;
    beg_ms_ = clock();
    count_ = 0;
  }
  switch (frame->format)
  {
  case AV_PIX_FMT_YUV420P:
    return Draw(frame->data[0], frame->linesize[0],  // Y
                frame->data[1], frame->linesize[1],  // U
                frame->data[2], frame->linesize[2]); // V
  case AV_PIX_FMT_ARGB:
    return Draw(frame->data[0], frame->linesize[0]);
  default:
    break;
  }
  return false;
}
